import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import Wrapper from '../wrapper';
import { ajax } from '../helper/helper';
class Settings extends Component {

    constructor(props) {
        super(props);
        var list = settings.emails.length > 0 ? settings.emails : [''];
        this.state = {
            mailList: list,
            trackingList: settings.tracking_id || [],
            platId: settings.plat_id || '',
            page: 'script',
            title: '1',
            showOk: [],
            showTracking: [],
            showPlatId: false
        }
    }
    componentDidMount() {
        var showOk = this.state.showOk,
            showTracking = this.state.showTracking,
            showPlatId = this.state.showPlatId,
            mailList = this.state.mailList,
            trackingList = this.state.trackingList,
            platId = this.state.platId;

        for (var i = 1; i < mailList.length; i++) {
            showOk[i] = true;
        }
        for (let j = 0; j < trackingList.length; j++) {
            showTracking[j] = true;
        }
        if (platId) {
            showPlatId = true;
        }
        this.setState({
            showOk: showOk,
            showPlatId: showPlatId,
            showTracking: showTracking
        })
    }
    onTab(params) {
        this.setState({
            page: params.page,
            title: params.title
        })
    }

    add() {
        var mailList = this.state.mailList,
            showOk = this.state.showOk;
        mailList.push('');
        showOk.push(false);
        this.setState({
            mailList: mailList
        })
    }

    addTracking() {
        let trackingList = this.state.trackingList,
            showTracking = this.state.showTracking;

        trackingList.push('');
        showTracking.push(false);
        this.setState({
            trackingList: trackingList
        })
    }

    del(index) {
        var mailList = this.state.mailList,
            showOk = this.state.showOk;
        if (mailList.length == 1) {
            mailList.splice(index, 1, "");
            showOk.splice(index, 1, false);
        } else {
            mailList.splice(index, 1);
            showOk.splice(index, 1);
        }
        if (!index && index != 0) {
            mailList.splice(0, 1, "");
            showOk.splice(0, 1);
        }
        this.setState({
            mailList: mailList,
            showOk: showOk
        })

    }

    delTracking(index) {
        let trackingList = this.state.trackingList,
            showTracking = this.state.showTracking;
        if (trackingList.length == 1) {
            trackingList.splice(index, 1, "");
            showTracking.splice(index, 1, false);
        } else {
            trackingList.splice(index, 1);
            showTracking.splice(index, 1);
        }
        if (!index && index != 0) {
            trackingList.splice(0, 1, "");
            showTracking.splice(0, 1);
        }
        this.setState({
            trackingList: trackingList,
            showTracking: showTracking
        })
    }

    delPlatId() {
        this.setState({
            platId: '',
            showPlatId: false
        })
    }

    updateValue(event, index) {
        var mailList = this.state.mailList,
            showOk = this.state.showOk,
            reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            email = event.target.value,
            repetition = false;
        for (var i = 0; i < mailList.length; i++) {
            if (mailList[i] == email) {
                repetition = true;
            }
        }
        if (index) {
            mailList[index] = event.target.value;
        } else {
            mailList[0] = event.target.value;
        }
        if (!repetition && email.length != 0 && reg.test(email)) {
            showOk[index] = true;
        } else {
            showOk[index] = false;
        }
        this.setState({
            mailList: mailList,
            showOk: showOk
        });
    }

    updateTracking(event, index) {
        var trackingList = this.state.trackingList,
            showTracking = this.state.showTracking,
            tracking = event.target.value,
            repetition = false;
        for (var i = 0; i < trackingList.length; i++) {
            if (trackingList[i] == tracking) {
                repetition = true;
            }
        }
        if (index) {
            trackingList[index] = event.target.value;
        } else {
            trackingList[0] = event.target.value;
        }
        if (!repetition && tracking.length != 0) {
            showTracking[index] = true;
        } else {
            showTracking[index] = false;
        }
        this.setState({
            trackingList: trackingList,
            showTracking: showTracking
        });
    }

    updatePlatId(event) {
        let showPlatId = true;
        if (!event.target.value) {
            showPlatId = false;
        }
        this.setState({
            platId: event.target.value,
            showPlatId: showPlatId
        });
    }

    opt() {
        document.getElementById('textarea').select();
    }
    copyValue() {
        document.getElementById('textarea').select();
        document.execCommand("Copy")

    }
    submit() {
        var url = '/settings/emails/save',
            showOk = this.state.showOk,
            mailList = this.state.mailList;

        var emailError = '';
        for (var i = 0; i < showOk.length; i++) {
            if (!showOk[i])
                emailError += '第' + (i + 1) + '个'
        }
        if (emailError == '') {
            ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                data: mailList,
                success: function (get_data, xml) {
                    alert('保存成功')
                }.bind(this),
                error: function (status) {
                    alert(status);
                }.bind(this)
            });
        } else if (typeof mailList == 'undefined') {
            alert('保存失败，请至少填一个邮箱地址');
        } else {
            alert('保存失败，' + emailError + '邮箱不正确')
        }

    }

    saveTrackingID() {
        var url = '/settings/tracking_id/save',
            showTracking = this.state.showTracking,
            trackingList = this.state.trackingList;
        var emailError = '';
        for (var i = 0; i < showTracking.length; i++) {
            if (!showTracking[i])
                emailError += '第' + (i + 1) + '个'
        }
        if (emailError == '') {
            ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                data: trackingList,
                success: function (get_data, xml) {
                    alert('保存成功')
                }.bind(this),
                error: function (status) {
                    alert(status);
                }.bind(this)
            });
        } else if (typeof trackingList == 'undefined') {
            alert('保存失败，请至少填一个trackingID');
        } else {
            alert('保存失败，' + emailError + 'trackingID不正确')
        }

    }

    savePlatId() {
        var url = '/settings/plat_id/save',
            showPlatId = this.state.showPlatId,
            platId = this.state.platId;
        platId = platId.split(',');
        var emailError = '';
        if (!showPlatId) {
            emailError = true;
        }
        ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            data: platId,
            success: function (get_data, xml) {
                alert('保存成功')
            }.bind(this),
            error: function (status) {
                alert(status);
            }.bind(this)
        });

    }

    render() {
        var self = this,
            mailList = this.state.mailList,
            trackingList = this.state.trackingList,
            platId = this.state.platId,
            add = this.add.bind(this),
            addTracking = this.addTracking.bind(this),
            del = this.del.bind(this),
            delTracking = this.delTracking.bind(this),
            delPlatId = this.delPlatId.bind(this),
            updateValue = this.updateValue.bind(this),
            updateTracking = this.updateTracking.bind(this),
            updatePlatId = this.updatePlatId.bind(this),
            submit = this.submit.bind(this),
            saveTrackingID = this.saveTrackingID.bind(this),
            savePlatId = this.savePlatId.bind(this),
            email = this.state.email,
            showOk = this.state.showOk,
            showTracking = this.state.showTracking,
            showPlatId = this.state.showPlatId,
            page = this.state.page,
            title = this.state.title,
            opt = this.opt.bind(this),
            copyValue = this.copyValue.bind(this),
            onTab = this.onTab.bind(this),
            textareaValue = '<!-- Start of LeadBar Embed Code -->\r\n       <script type="text/javascript" id="lb-script-loader" async defer src="http://leadbar.parllay.cn/lb/' + user.id + '.js"></script>\r\n<!-- End of LeadBar Embed Code -->';

        return (
            <Wrapper currentPage="settings">
                <section className="content-header">
                    <h1>
                        <span>设置</span>
                    </h1>
                </section>
                <div className="content" style={{ margin: '0 20px' }}>
                    <div className="row ">
                        <div className="col-md-12 row-border">
                            <div className="col-md-3 text-center">
                                <div className="div3">
                                    <div className={title == 1 ? " private-button cursor backg " : " private-button cursor "} onClick={() => onTab({ page: 'script', title: '1' })} >
                                        <h5 className="margin0">线索收集脚本安装</h5>
                                    </div>
                                    {/* <div className = {title == 4 ? "private-button cursor backg" : "private-button cursor"} >
                                    <h5 className = "margin0" onClick = {()=>onTab({page: 'tracking',title: '4'})}>TrackingID管理</h5>
                                </div> */}
                                    <div className={title == 5 ? "private-button cursor backg" : "private-button cursor"} onClick={() => onTab({ page: 'platId', title: '5' })}>
                                        <h5 className="margin0">PlatID管理</h5>
                                    </div>
                                    <div className={title == 2 ? " private-button cursor backg " : " private-button cursor "} onClick={() => onTab({ page: 'email', title: '2' })}>
                                        <h5 className="margin0">邮件通知</h5>
                                    </div>
                                    <div className={title == 3 ? "private-button cursor backg" : "private-button cursor"} onClick={() => onTab({ page: 'about', title: '3' })} >
                                        <h5 className="margin0">关于</h5>
                                    </div>
                                </div>
                            </div>
                            {(function () {
                                switch (page) {
                                    case 'script':
                                        return <div className="col-md-9 div1">
                                            <h5>跟踪代码</h5>
                                            <div className="row">
                                                <div className="col-xs-8">
                                                    <textarea id="textarea" className="col-xs-12" value={textareaValue} rows="5" onFocus={opt}>

                                                    </textarea>
                                                    <a className="btn btn-primary btn-flat" style={{ marginTop: '20px' }} onClick={copyValue}>复制</a>
                                                </div>
                                                <div className="col-xs-3">
                                                    <br />
                                                    <p className="color">如何使用？</p>
                                                    <p className="text">复制代码，将其粘贴到您需要搜集线索的页面中即可。</p>
                                                </div>
                                            </div>
                                        </div>
                                    case 'email':
                                        return <div className="col-xs-9 div1">
                                            <h4 className="margin-bottom1">线索搜集的电子邮件通知</h4>
                                            <div >
                                                <h5 className="col-xs-12"><b>发送到电子邮箱：</b></h5>
                                                <div id="div" className="form-group ">
                                                    <ul className="padding2">
                                                        {
                                                            mailList.length > 0 ? mailList.map(function (mail, index) {
                                                                return <li className="col-xs-12" key={'mails' + index}>
                                                                    <div className="col-xs-5" style={{ paddingLeft: 0 }}>
                                                                        <div className="has-success has-feedback padding-right">
                                                                            <input type="text" value={mail} className="form-control input1 " aria-describedby="inputSuccess2Status" onChange={function (e) { updateValue(e, index) }} />
                                                                            <span aria-hidden="true" className={showOk[index] ? "glyphicon glyphicon-ok form-control-feedback" : ""}></span>
                                                                        </div>
                                                                    </div>
                                                                    <div className="col-xs-2 padding"><span className="col-xs-4 glyphicon glyphicon-trash icon" onClick={function () { del(index) }}></span></div><br />
                                                                </li>
                                                            })
                                                                :
                                                                <li className="col-xs-12 ">
                                                                    <div className="col-xs-5 has-success has-feedback padding-right" style={{ paddingLeft: 0 }}>
                                                                        <input type="text" value={''} className="form-control input1 " aria-describedby="inputSuccess2Status" onChange={function (e) { updateValue(e) }} />
                                                                        <span aria-hidden="true" className={showOk[0] ? "glyphicon glyphicon-ok form-control-feedback" : ""}></span>
                                                                    </div>
                                                                    <div className="col-xs-2 padding"><span className="col-xs-4 glyphicon glyphicon-trash icon" onClick={function () { del() }}></span></div><br />
                                                                </li>
                                                        }
                                                    </ul>
                                                </div>
                                            </div>
                                            <div className="col-xs-5" style={{ textAlign: 'right' }}>
                                                <span className="padding-top0 cursor" onClick={add} ><span className="glyphicon glyphicon-plus icon2"></span> 添加另一个邮箱地址</span>
                                            </div>
                                            <div className="col-xs-12" style={{ marginTop: 20 }}>
                                                <a className="btn btn-primary btn-flat" onClick={submit}>保存</a>
                                            </div>
                                        </div>
                                    case 'tracking':
                                        return <div className="col-xs-8 div1">
                                            <h4 className="margin-bottom1">关联您的烽火台TrackingID</h4>
                                            <div className="row">
                                                <div >
                                                    <h5 className="col-xs-12"><b>请填写TrackingID：</b></h5>
                                                    <div id="div" className="form-group ">
                                                        <ul className="padding2">
                                                            {
                                                                trackingList.length > 0 ? trackingList.map(function (tracking, index) {
                                                                    return <li className="col-xs-12 " key={'tracking' + index}>
                                                                        <div className="col-xs-5 has-success has-feedback padding-right">
                                                                            <input type="text" value={tracking} className="form-control input1 " aria-describedby="inputSuccess2Status" onChange={function (e) { updateTracking(e, index) }} />
                                                                            <span aria-hidden="true" className={showTracking[index] ? "glyphicon glyphicon-ok form-control-feedback" : ""}></span>
                                                                        </div>
                                                                        <div className="col-xs-2 padding"><span className="col-xs-4 glyphicon glyphicon-trash icon" onClick={function () { delTracking(index) }}></span></div><br />
                                                                    </li>
                                                                })
                                                                    :
                                                                    <li className="col-xs-12 ">
                                                                        <div className="col-xs-5 has-success has-feedback padding-right">
                                                                            <input type="text" value={''} className="form-control input1 " aria-describedby="inputSuccess2Status" onChange={function (e) { updateTracking(e, 0) }} />
                                                                            <span aria-hidden="true" className={showTracking[0] ? "glyphicon glyphicon-ok form-control-feedback" : ""}></span>
                                                                        </div>
                                                                        <div className="col-xs-2 padding"><span className="col-xs-4 glyphicon glyphicon-trash icon" onClick={function () { delTracking() }}></span></div><br />
                                                                    </li>
                                                            }
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div className="col-xs-12">
                                                    <span className="padding-top0 cursor" onClick={addTracking} ><span className="glyphicon glyphicon-plus icon2"></span> 添加另一个TrackingID</span>
                                                </div>
                                                <div className="col-xs-5 text-center margin-top1">
                                                    <a className="btn btn-primary bn-color" onClick={saveTrackingID}>保存</a>
                                                </div>
                                            </div>
                                        </div>
                                    case 'platId':
                                        return <div className="col-xs-9 div1">
                                            <h4 className="margin-bottom1">关联您的公众号的PlatID</h4>
                                            <div className="row">
                                                <div >
                                                    <h5 className="col-xs-12"><b>请填写PlatID：</b></h5>
                                                    <div id="div" className="form-group ">
                                                        <ul className="padding2">
                                                            <li className="col-xs-12 ">
                                                                <div className="col-xs-5 has-success has-feedback padding-right">
                                                                    <input type="text" value={platId} className="form-control input1 " aria-describedby="inputSuccess2Status" onChange={function (e) { updatePlatId(e) }} />
                                                                    <span aria-hidden="true" className={showPlatId[0] ? "glyphicon glyphicon-ok form-control-feedback" : ""}></span>
                                                                </div>
                                                                <div className="col-xs-2 padding"><span className="col-xs-4 glyphicon glyphicon-trash icon" onClick={function () { delPlatId() }}></span></div><br />
                                                            </li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div className="col-xs-5 text-center">
                                                    <a className="btn btn-primary bn-color" onClick={savePlatId}>保存</a>
                                                </div>
                                            </div>
                                        </div>
                                    case 'about':
                                        return <div className="col-xs-9 div1">
                                            <h4 className="margin-bottom1">关于线索收集</h4>
                                            <div className="row">

                                                <h5 className="col-xs-10 "><b>把销售线索转化为业绩的五种方法:</b></h5>
                                                <p className="col-xs-10">方法一：销售电话</p>
                                                <p className="col-xs-10">方法二：电子邮件</p>
                                                <p className="col-xs-10">方法三：展览和会议</p>
                                                <p className="col-xs-10" >方法四：自己策划和活动</p>
                                                <p className="col-xs-10" >方法五：广告</p>
                                            </div>
                                        </div>
                                    default:
                                        return null
                                }
                            })()}

                        </div>
                    </div>
                </div>
            </Wrapper>
        );
    }
}

ReactDOM.render(
    <Settings />,
    document.getElementById('settings')
);